﻿using System;

using System.Collections.Generic;
using System.Text;
using System.IO;

namespace gpsmid_wince.util {
	class DictReader {
		//posittron: was private in original;
		public Tile dict;

		private static Logger logger = Logger.getInstance("DictReader", Logger.DEBUG);
		public static string basename;
		public Tile readData(sbyte zl) {
			//filename=@"E:\TMP\Osm2GpsMid\data\test.dat";
			string filename = basename + @"/dict-" + zl + ".dat";
			try {
				Stream is_ = File.OpenRead(filename);
				if (is_ == null) throw new IOException("Could not open " + filename);
				JavaDataInputStream ds = new JavaDataInputStream(is_);
				if (!"DictMid".Equals(ds.readUTF())) {
					throw new IOException("Not a DictMid-file");
				}
				dict = readTile(ds, 1, zl);
				ds.close();
				//t.setDict(dict, zl);
			} catch (IOException ioe) {
				// Special case zoom level 4, which is the routing zoom level.
				// If routing was disabled in Osm2GpsMid, this file won't
				// exist. Give a more helpful message.
				if (zl == 4) {
					logger.info("Routing is not enabled in this midlet");
					return null;
				} else {
					throw ioe;
				}
			}
			return dict;
		}

		public static Tile readTile(JavaDataInputStream ds, int depth, sbyte zl) {
			Tile dict = null;
			try {				
				
				sbyte type = ds.readByte();
				switch (type) {
					case Tile.TYPE_MAP:
						dict = new SingleTile(ds, 1, zl);
						break;
					case Tile.TYPE_CONTAINER:
						dict = new ContainerTile(ds, 1, zl);
						break;
					case Tile.TYPE_EMPTY:
						// empty tile;
						break;
					case Tile.TYPE_FILETILE:
						logger.debug("!!reading file data");
						dict = new FileTile(ds, 1, zl);
						break;
					case Tile.TYPE_ROUTEDATA:
						logger.debug("!!reading route data");
						//dict = new RouteTile(ds, 1, zl);
						break;
					case Tile.TYPE_ROUTECONTAINER:
						logger.debug("!!reading routecontainer data");
						//dict = new RouteContainerTile(ds, 1, zl);
						break;
					default:
						logger.error("wrongTileType:"+type);
    					throw new IOException("wrong TileType:"+type);
				}
				
			} catch (IOException ioe) {
				// Special case zoom level 4, which is the routing zoom level.
				// If routing was disabled in Osm2GpsMid, this file won't
				// exist. Give a more helpful message.
				if (zl == 4) {
					logger.info("Routing is not enabled in this midlet");
					return null;
				} else {
					throw ioe;
				}
			}
			return dict;
		}
	
		
	}

}
